package com.zbkj.crmeb.category.controller;

import java.util.List;
import java.util.Objects;

import cn.hutool.core.util.StrUtil;
import com.common.CheckAdminToken;
import com.crmeb.core.utils.RedisUtil;
import com.zbkj.crmeb.chant.model.CategoryMatch;
import com.zbkj.crmeb.merchant.admin.controller.AdminBaseController;
import com.zbkj.crmeb.system.model.SystemAdmin;
import com.zbkj.crmeb.system.service.SystemAdminService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.common.CommonPage;
import com.common.PageParamRequest;
import com.constants.Constants;
import com.crmeb.core.common.CommonResult;
import com.crmeb.core.exception.CrmebException;
import com.utils.CrmebUtil;
import com.zbkj.crmeb.category.model.Category;
import com.zbkj.crmeb.category.request.CategoryRequest;
import com.zbkj.crmeb.category.request.CategorySearchRequest;
import com.zbkj.crmeb.category.service.CategoryMenuTypeService;
import com.zbkj.crmeb.category.service.CategoryService;
import com.zbkj.crmeb.category.vo.CategoryTreeVo;
import com.zbkj.crmeb.system.service.SystemAttachmentService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

import javax.servlet.http.HttpServletRequest;

/**
 * 分类服务
 * @Description: 
 * @author daigb
 * @date 2021-04-16
 */
@RestController
@RequestMapping("api/admin/category")
@Api(tags = "分类服务")

public class CategoryController extends AdminBaseController{

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private SystemAttachmentService systemAttachmentService;

    @Autowired
    private CategoryMenuTypeService categoryMenuTypeService;

    @Autowired
    CheckAdminToken checkAdminToken;
    @Autowired
    RedisUtil redisUtil;
    @Autowired
    private SystemAdminService systemAdminService;

    /**
     * 分页显示分类表
     * @param request 搜索条件
     * @param pageParamRequest 分页参数
     * @author Mr.Zhang
     * @since 2020-04-16
     */
    @ApiOperation(value = "分页列表")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public CommonResult<CommonPage<Category>> getList(@ModelAttribute CategorySearchRequest request, @ModelAttribute PageParamRequest pageParamRequest) {
        CommonPage<Category> categoryCommonPage = CommonPage.restPage(categoryService.getList(request, pageParamRequest));
        return CommonResult.success(categoryCommonPage);
    }

    /**
     * 新增分类表
     * @param categoryRequest 新增参数
     * @author Mr.Zhang
     * @since 2020-04-16
     */
    @ApiOperation(value = "新增")
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public CommonResult<String> save(@Validated CategoryRequest categoryRequest, HttpServletRequest request) {
        if(Objects.equals(categoryRequest.getType(),1)){
            throw new CrmebException("该分类类型已取消");
        }
        Category category = new Category();
        //检测标题是否存在
        if (categoryService.checkName(categoryRequest.getName(), category.getType()) > 0) {
            throw new CrmebException("此分类已存在");
        }
        BeanUtils.copyProperties(categoryRequest, category);
        category.setPath(categoryService.getPathByPId(category.getPid()));
        category.setExtra(systemAttachmentService.clearPrefix(category.getExtra()));
        if (Constants.CATEGORY_TYPE_ATTACHMENT != category.getType()) {
            category.setMerId(null);
        }
        category.setMerId(getMerId(request));

        boolean b = categoryService.save(category);
        if (b && Constants.CATEGORY_TYPE_MENU == category.getType()) {
            // 保存菜单身份类型
            categoryRequest.setId(category.getId());
            categoryMenuTypeService.addCategoryMenuType(categoryRequest);
        }

        return b ? CommonResult.success() : CommonResult.failed();
    }

    /**
     * 删除分类表
     *
     * @param id Integer
     * @author Mr.Zhang
     * @since 2020-04-16
     */
    @ApiOperation(value = "删除")
    @RequestMapping(value = "/delete", method = RequestMethod.GET)
    @ApiImplicitParam(name = "id", value = "分类ID")
    @Transactional(rollbackFor = Exception.class)
    public CommonResult<String> delete(@RequestParam(value = "id") Integer id) {
        List<Integer> list = categoryService.getAllCateIds(id);
        boolean b = categoryService.delete(id) > 0;
        // 删除子表
        if (CollectionUtils.isNotEmpty(list)) {
            categoryMenuTypeService.deleteByCategoryId(list);
        }
        return b ? CommonResult.success() : CommonResult.failed();
    }

    /**
     * 修改分类表
     * @param id integer id
     * @param categoryRequest 修改参数
     * @author Mr.Zhang
     * @since 2020-04-16
     */
    @ApiOperation(value = "修改")
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    @ApiImplicitParam(name = "id", value = "分类ID")
    public CommonResult<String> update(@RequestParam Integer id, @ModelAttribute CategoryRequest categoryRequest) {
        if(Objects.equals(categoryRequest.getType(),1)){
            throw new CrmebException("该分类类型已取消");
        }
        if (null == id || id <= 0)
            throw new CrmebException("id 参数不合法");
        categoryRequest.setExtra(systemAttachmentService.clearPrefix(categoryRequest.getExtra()));
        if (Constants.CATEGORY_TYPE_ATTACHMENT != categoryRequest.getType()) {
            categoryRequest.setMerId(null);
        }

        boolean b = categoryService.update(categoryRequest, id);
        if (b && Constants.CATEGORY_TYPE_MENU == categoryRequest.getType()) {
            // 修改菜单身份类型
            categoryMenuTypeService.updateCategoryMenuType(id, categoryRequest.getIdentityTypes());
        }
        return b ? CommonResult.success() : CommonResult.failed();
    }

    /**
     * 查询分类表信息
     * @param id Integer
     * @author Mr.Zhang
     * @since 2020-04-16
     */
    @ApiOperation(value = "详情")
    @RequestMapping(value = "/info", method = RequestMethod.GET)
    @ApiImplicitParam(name = "id", value = "分类ID")
    public CommonResult<Category> info(@RequestParam(value = "id") Integer id) {
        Category category = categoryService.getById(id);
        return CommonResult.success(category);
    }

    /**
     * 查询分类表信息
     *
     * @author Mr.Zhang
     * @since 2020-04-16
     */
    @ApiOperation(value = "获取tree结构的列表")
    @RequestMapping(value = "/list/tree", method = RequestMethod.GET)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "type", value = "1: 产品分类，2: 附件分类，3: 文章分类， 4: 设置分类， 5: 菜单分类， 6: 配置分类， 7: 秒杀配置, 8: buyer分类 9: Europe分类 10: Tmall分类", example = "1"),
            @ApiImplicitParam(name = "status", value = "-1=全部，0=未生效，1=已生效", example = "1"),
            @ApiImplicitParam(name = "identityType", value = "身份类型：1：平台；2：商家；3：一级服务商；4：二级服务商；5：供应商", example = "1"),
            @ApiImplicitParam(name = "merId", value = "商户id，type=2时传递")})
    public CommonResult<List<CategoryTreeVo>> getListTree(@RequestParam(name = "type") Integer type,
                                                          @RequestParam(name = "status") Integer status,
                                                          @RequestParam(name = "identityType",required = false) Integer identityType,
                                                          @RequestParam(name = "merId", required = false) Integer merId, HttpServletRequest request) {
        String token = checkAdminToken.getTokenFormRequest(request);
        SystemAdmin admin = systemAdminService.lambdaQuery().eq(SystemAdmin::getNowToken, token).one();

        identityType = identityType==null ? admin.getIdentityType() : identityType;
        if(identityType != 1){
            merId = getMerId(request);
        }
        List<CategoryTreeVo> listTree = categoryService.getListTreeDetail(type, status, identityType, merId);
        return CommonResult.success(listTree);
    }

    /**
     * 根据分类id集合获取分类数据
     * @param ids String id集合字符串
     * @since 2020-04-16
     */
    @ApiOperation(value = "根据id集合获取分类列表")
    @RequestMapping(value = "/list/ids", method = RequestMethod.GET)
    @ApiImplicitParam(name = "ids", value = "分类id集合")
    public CommonResult<List<Category>> getByIds(@Validated @RequestParam(name = "ids") String ids) {
        return CommonResult.success(categoryService.getByIds(CrmebUtil.stringToArray(ids)));
    }

    @ApiOperation(value = "获取所有一级分类")
    @RequestMapping(value = "/mainCategory", method = RequestMethod.GET)
    public CommonResult<List<CategoryMatch>> getMainCategoryList() {
        return CommonResult.success(categoryService.getMainCategoryList());
    }

}
